'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Modal,
  Form,
  Tag,
  Popconfirm,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Select,
  Space,
  Statistic,
  Empty,
  Progress,
  List
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { tagService, type Tag as ServiceTag } from '@/service/tag.service';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;

interface TagItem extends ServiceTag {
  usageCount: number;
  isHot?: boolean;
}

const TagManagement: React.FC = () => {
  // 状态定义
  const [tags, setTags] = useState<TagItem[]>([]);
  const [filteredTags, setFilteredTags] = useState<TagItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentTag, setCurrentTag] = useState<TagItem | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [tagForm] = Form.useForm();
  const [filterType, setFilterType] = useState('all'); // all, hot, unused
  const [hotTags, setHotTags] = useState<TagItem[]>([]); // 热门标签数据

  // 加载标签数据
  const fetchTags = async () => {
    setLoading(true);
    try {
      const response = await tagService.getTagList();
      const tagsData = Array.isArray(response) ? response : response.data || [];
      // 添加使用次数和热门标识
      const tagsWithMeta = tagsData.map(tag => ({
        ...tag,
        isHot: (tag.usageCount ?? 0) >= 10,
      }));
      setTags(tagsWithMeta);
      setFilteredTags(tagsWithMeta);
    } catch (error) {
      console.error('获取标签列表失败:', error);
      message.error('获取标签列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载热门标签
  const fetchHotTags = async () => {
    try {
      const data = await tagService.getPopularTags(10);
      const hotTagsData = Array.isArray(data) ? data : [];
      const hotTagsWithMeta = hotTagsData.map(tag => ({
        ...tag,
        isHot: true
      }));
      setHotTags(hotTagsWithMeta);
    } catch (error) {
      console.error('获取热门标签失败:', error);
    }
  };

  useEffect(() => {
    fetchTags();
    fetchHotTags();
  }, []);

  // 筛选标签
  useEffect(() => {
    let filtered = [...tags];
    
    // 按类型筛选
    if (filterType === 'hot') {
      filtered = filtered.filter(tag => tag.isHot);
    } else if (filterType === 'unused') {
      filtered = filtered.filter(tag => tag.usageCount === 0);
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      filtered = filtered.filter(tag => 
        tag.name.toLowerCase().includes(lowerSearchText)
      );
    }
    
    // 按使用次数排序
    filtered.sort((a, b) => b.usageCount - a.usageCount);
    
    setFilteredTags(filtered);
  }, [tags, searchText, filterType]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理添加标签
  const handleAddTag = () => {
    setCurrentTag(null);
    tagForm.resetFields();
    setIsModalVisible(true);
  };

  // 处理编辑标签
  const handleEditTag = (tag: TagItem) => {
    setCurrentTag(tag);
    tagForm.setFieldsValue({
      name: tag.name
    });
    setIsModalVisible(true);
  };

  // 处理保存标签
  const handleSaveTag = async () => {
    try {
      const values = await tagForm.validateFields();
      
      if (currentTag) {
        // 编辑现有标签
        await tagService.updateTag(currentTag.id, {
          name: values.name
        });
        message.success('标签更新成功');
      } else {
        // 添加新标签
        await tagService.createTag({
          name: values.name
        });
        message.success('标签添加成功');
      }
      setIsModalVisible(false);
      tagForm.resetFields();
      setCurrentTag(null);
      // 重新加载数据
      fetchTags();
    } catch (error: any) {
      console.error('保存标签失败:', error);
      message.error(error?.message || '保存标签失败');
    }
  };

  // 处理删除标签
  const handleDeleteTag = async (id: number) => {
    const tag = tags.find(t => t.id === id);
    if (tag && (tag.usageCount || 0) > 0) {
      message.error('该标签正在使用中，无法删除');
      return;
    }
    
    try {
      await tagService.deleteTag(id);
      message.success('标签删除成功');
      // 重新加载数据
      fetchTags();
      fetchHotTags();
    } catch (error: any) {
      console.error('删除标签失败:', error);
      message.error(error?.message || '删除标签失败');
    }
  };

  // 处理标签状态切换
  const handleToggleStatus = async (id: number, currentStatus: number) => {
    const newStatus = currentStatus === 1 ? 0 : 1;
    try {
      await tagService.updateTagStatus(id, newStatus);
      message.success(`标签已${newStatus === 1 ? '启用' : '禁用'}`);
      fetchTags();
      fetchHotTags();
    } catch (error: any) {
      console.error('更新标签状态失败:', error);
      message.error(error?.message || '更新标签状态失败');
    }
  };

  // 处理清理未使用标签
  const handleCleanUnused = () => {
    const unusedTagsCount = tags.filter(tag => tag.usageCount === 0).length;
    if (unusedTagsCount === 0) {
      message.info('没有未使用的标签需要清理');
      return;
    }
    
    Modal.confirm({
      title: '确认清理',
      content: `确定要删除所有未使用的标签吗？共 ${unusedTagsCount} 个标签。`,
      onOk: () => {
        const updatedTags = tags.filter(tag => tag.usageCount > 0);
        setTags(updatedTags);
        message.success(`成功清理 ${unusedTagsCount} 个未使用标签`);
      }
    });
  };

  // 计算统计数据
  const totalTags = tags.length;
  const hotTagsCount = tags.filter(tag => tag.isHot).length;
  const unusedTagsCount = tags.filter(tag => tag.usageCount === 0).length;
  const totalUsage = tags.reduce((sum, tag) => sum + tag.usageCount, 0);

  // 标签列表列配置
  const columns: ColumnsType<TagItem> = [
    {
      title: '标签名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name: string, record: TagItem) => (
        <div>
          <Tag color={record.isHot ? 'red' : 'blue'} style={{ fontSize: '14px', padding: '4px 10px' }}>
            {name}
            {record.isHot && <span style={{ marginLeft: '4px' }}>🔥</span>}
          </Tag>
        </div>
      )
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      width: 100,
      align: 'center',
      render: (count: number) => (
        <Text type={count > 0 ? 'success' : undefined}><strong>{count}</strong></Text>
      )
    },
    {
      title: '占比',
      key: 'percentage',
      width: 150,
      render: (_, record: TagItem) => {
        const percentage = totalUsage > 0 ? Math.round((record.usageCount / totalUsage) * 100) : 0;
        return (
          <Progress percent={percentage} size="small" />
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      align: 'center',
      render: (isActive: number) => (
        <Tag color={isActive === 1 ? 'green' : 'red'}>
          {isActive === 1 ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (time: string) => new Date(time).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      render: (_, record: TagItem) => (
        <Space size="small">
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEditTag(record)}>
            编辑
          </Button>
          <Button 
            size="small" 
            type={record.isActive === 1 ? 'default' : 'primary'}
            onClick={() => handleToggleStatus(record.id, record.isActive ?? 1)}
          >
            {record.isActive === 1 ? '禁用' : '启用'}
          </Button>
          <Popconfirm
            title="确定要删除此标签吗?"
            onConfirm={() => handleDeleteTag(record.id)}
            okText="确定"
            cancelText="取消"
            disabled={record.usageCount > 0}
          >
            <Button 
              size="small" 
              danger 
              icon={<DeleteOutlined />} 
              disabled={record.usageCount > 0}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>标签管理</Title>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 标签统计卡片 */}
        <Col span={6}>
          <Card title="标签统计概览" variant="outlined">
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="总标签数" value={totalTags} suffix="个" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="热门标签" value={hotTagsCount} suffix="个" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="未使用标签" value={unusedTagsCount} suffix="个" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Statistic title="总使用次数" value={totalUsage} suffix="次" />
            </div>
            
            <Divider style={{ margin: '16px 0' }} />
            
            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
              <Button 
                danger 
                icon={<DeleteOutlined />} 
                onClick={handleCleanUnused}
                style={{ width: '100%' }}
                disabled={unusedTagsCount === 0}
              >
                清理未使用标签
              </Button>
            </div>
          </Card>
        </Col>
        
        {/* 热门标签统计 */}
        <Col span={8}>
          <Card title="热门标签 TOP 10" variant="outlined">
            {hotTags.length > 0 ? (
              <List
                dataSource={hotTags.slice(0, 10)}
                renderItem={(item, index) => (
                  <List.Item>
                    <List.Item.Meta
                      title={
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                          <span style={{ width: '20px', textAlign: 'right' }}>{index + 1}.</span>
                          <Tag color="red" style={{ fontSize: '14px', padding: '4px 10px' }}>
                            {item.name}
                          </Tag> 
                          <Text type="success">{item.usageCount} 次使用</Text>
                        </div>
                      }
                      description={
                        <Progress 
                          percent={totalUsage > 0 ? (item.usageCount / totalUsage) * 100 : 0} 
                          size="small" 
                          showInfo={false}
                          strokeColor="#ff4d4f"
                        />
                      }
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无热门标签" />
            )}
          </Card>
        </Col>
        
        {/* 标签列表 */}
        <Col span={10}>
          <Card 
            title="标签列表"
            variant="outlined"
            extra={
              <div style={{ display: 'flex', gap: '8px' }}>
                <Input
                  placeholder="搜索标签名称"
                  allowClear
                  onPressEnter={(e) => handleSearch(e.currentTarget.value)}
                  style={{ width: 200 }}
                  suffix={<SearchOutlined onClick={() => {
                    const input = document.querySelector('input[placeholder="搜索标签名称"]') as HTMLInputElement;
                    if (input) handleSearch(input.value);
                  }} />}
                />
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddTag}>
                  添加标签
                </Button>
              </div>
            }
          >
            <Select
              defaultValue="all"
              onChange={setFilterType}
              style={{ marginBottom: '16px', width: 150 }}
            >
              <Option value="all">全部标签</Option>
              <Option value="hot">热门标签</Option>
              <Option value="unused">未使用标签</Option>
            </Select>
            
            <Table
              columns={columns}
              dataSource={filteredTags}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 标签编辑/添加模态框 */}
      <Modal
        title={currentTag ? '编辑标签' : '添加标签'}
        open={isModalVisible}
        onOk={handleSaveTag}
        onCancel={() => {
          setIsModalVisible(false);
          tagForm.resetFields();
          setCurrentTag(null);
        }}
        okText="保存"
        cancelText="取消"
        width={400}
      >
        <Form form={tagForm} layout="vertical">
          <Form.Item
            label="标签名称"
            name="name"
            rules={[{ required: true, message: '请输入标签名称' }, { min: 1, max: 30, message: '标签名称长度应在 1-30 个字符之间' }]}
          >
            <Input placeholder="请输入标签名称" />
          </Form.Item>
        </Form>
      </Modal>

    </div>
  );
};

export default TagManagement;
